import * as React from 'react'
import { Link, withRouter ,RouteComponentProps} from 'react-router-dom'
import {Capsule} from '../Capsule/Capsule'
import style from "./style.less";

interface ids {
    id :string
}

class Put extends React.Component<RouteComponentProps,ids> {
    nameref: React.RefObject<HTMLInputElement>;
    mailref: React.RefObject<HTMLInputElement>;
    timeref: React.RefObject<HTMLInputElement>;
    conref: React.RefObject<HTMLTextAreaElement>;
    tipref: React.RefObject<HTMLTextAreaElement>;
    e_name: React.RefObject<HTMLDivElement>
    e_email: React.RefObject<HTMLDivElement>
    e_con: React.RefObject<HTMLDivElement>

    constructor(props) {
        super(props);
        this.state = ({
            id : ''
        })
        this.nameref = React.createRef()
        this.mailref = React.createRef()
        this.timeref = React.createRef()
        this.conref = React.createRef()
        this.tipref = React.createRef()
    }

    componentDidMount() {
        this.timeref.current.value = this.getNowDate()
    }

    GetFormElement() {
        let capsule:Capsule = {name: '', email: '',time: '',content: '', tip:''}

        // let name:HTMLInputElement = document.querySelector('.name')
        let name_value = this.nameref.current.value
        // let mail:HTMLInputElement = document.querySelector('.e_mail')
        let mail_value = this.mailref.current.value
        // let time:HTMLInputElement = document.querySelector('.time')
        let time_value = this.timeref.current.value
        // let nr:HTMLInputElement = document.querySelector('.neirong')
        let nr_value = this.conref.current.value
        // let tip:HTMLInputElement = document.querySelector('.tip')
        let tip_value =this.tipref.current.value
        if ( name_value.length !== 0 )
            capsule.name = name_value
        if ( mail_value.length !== 0 )
            capsule.email = mail_value
        if ( time_value.length !== 0 )
            capsule.time = time_value
        if ( nr_value.length !== 0 )
            capsule.content = nr_value
        capsule.tip = tip_value
        console.log("123")
        if (( this.checkemail(mail_value) === true) &&( name_value.length !== 0 ) && ( mail_value.length !== 0 ) && ( time_value.length !== 0 ) && ( nr_value.length !== 0 )){{
            return capsule
        }
        }else {
            return null
        }
    }

    checkemail(str:string) {
        let Expression = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/;
        if (Expression.test(str) == true) {
            return true;
        } else {
            return false;
        }
    }

    async  write(value: Capsule) {
        // let str:string
        return await fetch('http://127.0.0.1:3280/api/add',{
            method:'post',//改成post
            mode: 'cors',//跨域
            headers: {//请求头
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: JSON.stringify(value) //向服务器发送的数据
        })
            // .then(res =>  { res.text().then(val => {
            // console.log('123')
            // console.log(JSON.parse(val).id.toString())
            // // this.setState({
            // //     id:JSON.parse(val).id.toString()
            // // })
            // localStorage.setItem('key',JSON.parse(val).id.toString())
            // this.props.history.push(`/put_done/${JSON.parse(val).id.toString()}`);
            // this.props.history.push('/put_done')
            // this.props.history.push(`/put_done`);
            // str = JSON.parse(val).id.toString()
            // return str
            // })
            // }
        // )

    }

    err() {
        // let name:HTMLInputElement = document.querySelector('.name')
        let name_value = this.nameref.current.value
        // let mail:HTMLInputElement = document.querySelector('.e_mail')
        let mail_value =this.mailref.current.value
        // let nr:HTMLInputElement = document.querySelector('.neirong')
        let nr_value = this.conref.current.value
        // let ename:HTMLElement = document.querySelector('.err_name')
        let that = this
        let ename = that.e_name.current
        // let email:HTMLElement = document.querySelector('.err_mail')
        let email = that.e_email.current
        // let enr:HTMLElement = document.querySelector('.err_nr')
        let enr = that.e_con.current

        if (!this.checkemail(mail_value)){
            if (mail_value.length !== 0){
                email.innerText = "邮箱 必须是一个有效的电子邮箱地址."
            }else {
                email.innerText = '邮箱 必须填写.  123'
            }
        }

        if (name_value.length === 0)
            ename.style.display = 'block'
        else
            ename.style.display = 'none'
        if (mail_value.length === 0)
            email.style.display = 'block'
        else{
            if (!this.checkemail(mail_value)){
                email.innerText = "邮箱 必须是一个有效的电子邮箱地址."
                email.style.display = 'block'
            }else {
                email.innerText = '邮箱 必须填写.  123'
                email.style.display = 'none'
            }
        }

        if (nr_value.length === 0)
            enr.style.display = 'block'
        else
            enr.style.display = 'none'
    }

    async put() {
        console.log('2')
        let c: Capsule | null = this.GetFormElement()
        if (c !== null) {
            let response = await this.write(c)
            let str:string = JSON.parse(await response.text()).id
            localStorage.setItem('key',str)
            // let x = '123'

            // await this.props.history.push(`/put_done/${this.state.id}`);
            // this.props.history.push(`/put_done/${this.state.id}`);
            return false
        } else {
            this.err()
            return false
        }
    }

    getNowDate(): string {
        const date = new Date();
        let month: string | number = date.getMonth() + 1;
        let strDate: string | number = date.getDate();
        let hour: string | number = date.getHours();
        let min: string | number = date.getMinutes();
        let sec: string | number = date.getSeconds();

        if (month <= 9) {
            month = "0" + month;
        }

        if (strDate <= 9) {
            strDate = "0" + strDate;
        }

        if (hour <= 9)
            hour = "0" + hour;

        if (min <= 9)
            min = "0" + min;

        if (sec <= 9)
            sec = "0" + sec;

        return date.getFullYear() + "-" + month + "-" + strDate + " "
            + hour + ":" + min + ":" + sec;
    }

    render() {
        return (
            <div>
                <header className={style.top}>
                    <div className={style.top_main}>
                        <Link className={style.top_img} to="/">
                            时间胶囊
                        </Link>
                        <div>
                            <Link className={style.top_back} to="/">首页</Link>
                            <Link className={style.top_put} to="/put">添加</Link>
                            <Link className={style.top_open} to="/open">打开</Link>
                        </div>
                    </div>
                </header>
                <main className={style.bottom}>
                    <div className={style.container}>
                        <h1 className={style.page_header}>添加胶囊</h1>
                        <div className={style.main}>
                            <form name="form" action="/put_done" className={style.form} onSubmit={()=>{return this.put()}}>
                                <label>你的名字</label>
                                <div className={style.err_name} ref={this.e_name}>名字 必须填写.</div>
                                <input className={style.name} id="name" ref={this.nameref} name="name" onChange={()=>{}} type="text"/>
                                <label>你的邮箱</label>
                                <div className={style.err_mail} ref={this.e_email} >邮箱 必须填写.</div>
                                <input id="e-mail" className={style.e_mail} ref={this.mailref} onChange={()=>{}} name="email"  type="text"/>
                                <label>打开时间</label>
                                <input id="time" className={style.time} name="time" ref={this.timeref} onChange={()=>{}} type="text"/>
                                <span className={style.tips}>打开时间之前，胶囊内容是看不到的。</span>
                                <label>胶囊内容</label>
                                <div className={style.err_nr} ref={this.e_con} >内容 必须填写.</div>
                                <textarea id="neirong" className={style.neirong} ref={this.conref} onChange={()=>{}} name="content"  rows={8}
                                          cols={50}/>
                                <span className={style.tips}>胶囊内容不能超过5000字。</span>
                                <label className={style.tips_label} >未到期提示信息</label>
                                <textarea id="tip" className={style.tip} ref={this.tipref} onChange={()=>{}} name="tips"  rows={3}
                                          cols={50}/>
                                <span className={style.tips}>在 打开时间 之前打开胶囊，会看到提示信息。</span>
                                <p className={style.add}>
                                    <input type="submit" value="添加胶囊"/>
                                </p>
                            </form>
                        </div>
                    </div>
                </main>
            </div>
        )
    }
}

export default withRouter(Put)
